package server;

import java.io.File;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.NoSuchAlgorithmException;


import org.jets3t.service.ServiceException;
import org.jets3t.service.acl.Permission;
import org.jets3t.service.acl.gs.AllUsersGrantee;
import org.jets3t.service.acl.gs.GSAccessControlList;
import org.jets3t.service.impl.rest.httpclient.GoogleStorageService;
import org.jets3t.service.model.S3Object;
import org.jets3t.service.model.StorageOwner;
import org.jets3t.service.security.GSCredentials;

import worker.SamplesUtils;

public class Image extends Thread{
	String imageUrl = "";
	String destinationFile = "";
	private static final String BUCKET_NAME = "cdn.as7.org";
	public Image(String imageUrl, String destinationFile)
	{
		this.imageUrl = imageUrl;
		this.destinationFile = destinationFile;
		this.start();
	}
	public void run() {
		URL url;
		try {
			url = new URL(imageUrl);
			InputStream is = url.openStream();
			OutputStream os = new FileOutputStream(destinationFile);
			
			GSCredentials gsCredentials = SamplesUtils.loadGSCredentials();

			// To communicate with Google Storage use the GoogleStorageService.
			GoogleStorageService gsService = new GoogleStorageService(gsCredentials);
			
			byte[] b = new byte[2048];
			int length;

			while ((length = is.read(b)) != -1) {
				os.write(b, 0, length);
			}

			is.close();
			os.close();
			
			File fileData = new File(destinationFile);
			GSAccessControlList bucketAcl = new GSAccessControlList();
			bucketAcl.setOwner(new StorageOwner("00b4903a97e7b7343c5d070c4bc6479e63a9de76f9884e651e136798c72f7e18", "Ha Bogay"));
			
			S3Object fileObject = new S3Object(fileData);
			
			bucketAcl.grantPermission(new AllUsersGrantee(), Permission.PERMISSION_READ);
			
			fileObject.setAcl(bucketAcl);
			gsService.putObject(BUCKET_NAME, fileObject);
			Process process;
			@SuppressWarnings("unused")
			BufferedReader buf;
			process = Runtime.getRuntime().exec("rm -f "+destinationFile);
			buf = new BufferedReader(new InputStreamReader(
			process.getInputStream()));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}	
}
